package com.haoxuer.discover.user.freemaker;

import com.haoxuer.discover.common.utils.DirectiveUtils;
import com.haoxuer.discover.user.api.apis.MenuApi;
import com.haoxuer.discover.user.api.domain.list.MenuList;
import com.haoxuer.discover.user.api.domain.request.MenuSearchRequest;
import com.haoxuer.discover.user.api.domain.simple.MenuSimple;
import com.haoxuer.discover.user.data.entity.Menu;
import com.haoxuer.discover.user.data.service.MenuService;
import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 查找某个节点下一层的菜单
 */
public class MenusDirective implements TemplateDirectiveModel {
  
  @Autowired
  MenuApi menuService;
  
  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {
    
    // 其实完全可以不用它，params是个Map，自己通过key取值就可以了，做一下空值判断
    Integer id = DirectiveUtils.getInt("id", params);
    Integer size = DirectiveUtils.getInt("size", params);


    MenuSearchRequest request=new MenuSearchRequest();
    request.setParent(id);
    request.setSize(100);
    request.setFetch(1);
    request.setSortField("sortNum");
    request.setSortMethod("asc");
    MenuList menuList = menuService.menus(request);

    List<MenuSimple> menus=menuList.getList();

    Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
    paramWrap.put("list", ObjectWrapper.DEFAULT_WRAPPER.wrap(menus));
    Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
    if (body != null) {
      body.render(env.getOut());
    }
    DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
    
  }
}